//
//  GameViewController.swift
//  1010
//
//  Created by 米明 on 15/7/8.
//  Copyright (c) 2015年 米明. All rights reserved.
//

import UIKit
import Social

var SCREEN_SIZE = UIScreen.main.bounds.size
//10*10个小格子
var squares : [UIView]=[]
//创建 一个 画布
var gameView : UIView!
//小格子上是否以创建方块 0无1有
var squareStatus : [Int]=[]
//用于存放在棋盘上生成的小方块
var newSquares : [UIView]=[]
//存放三个diamond
var diamonds : [Diamond]=[]
//gameView
var selfView : UIView!

//格子宽
func sqWidth() -> CGFloat {
    return gameView.frame.size.width/10.0
}

let DIAMOND_TAG = 1001
let NEWSQUARE_TAG = 2001


class GameViewController: UIViewController {

    var statusBar:GameStatusBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        LYSoundManager.manager.playDefaultBGM()
        // Do any additional setup after loading the view.
    }

    //MARK: 游戏状态栏
    func gameStatusBar() {
        statusBar = GameStatusBar(frame: CGRect(x: 0, y: 10, width: SCREEN_SIZE.width, height: 60))
        statusBar.pauseActionBack {
            self.pause()
        }
        self.view.addSubview(statusBar)
    }
    //MARK: 暂停
    func pause() {
        
        LYSoundManager.manager.stopMusic()
        
        menu = MenuView(frame: UIScreen.main.bounds)
        menu.showPauseMenu()
        
        //计分板
        menu.scoreCallBack {
            LYProgressHUD.showMessage(message: "暂无排名!")
        }
        
        //Home
        menu.settingCallBack {
            self.dismiss(animated: false, completion: nil)
            self.setUpData()
        }
        
        //继续
        menu.startCallBack {
            self.menu.dismiss()
            LYSoundManager.manager.playDefaultBGM()
        }
        
        //重来
        menu.shareCallBack {
            self.setUpData()
            self.squareAnimation()
            self.menu.dismiss()
            LYSoundManager.manager.playDefaultBGM()
        }

        self.view.addSubview(menu)
    }
    
    //MARK: 初始化UI
    func setUpUI() {
        
        selfView = self.view
        
        //游戏状态栏
        gameStatusBar()
        
        //画布
        createGameView()
        
        //画格子
        drawSquares()
    
    }
    
    //MARK: 画布
    func createGameView() {
        //画布一些参数
        let gWidth = SCREEN_SIZE.height/2
        let gHeight = gWidth
        gameView = UIView(frame: CGRect(x: 0, y: 0, width: gWidth, height: gHeight))
        gameView.center = CGPoint(x: SCREEN_SIZE.width/2.0, y: SCREEN_SIZE.height/2.0)
        //gameView?.backgroundColor=UIColor.lightGrayColor()
        view.addSubview(gameView)
    }
    
    //MARK :画格子
    func drawSquares() {
    
        //创建10*10的格子
        for i in 0..<10 {
            for j in 0..<10 {
                let square = UIView(frame: CGRect(x: gameView.frame.origin.x+sqWidth()*CGFloat(j),y: gameView.frame.origin.y+sqWidth()*CGFloat(i), width: sqWidth(), height: sqWidth()))
                square.backgroundColor = customColor(red: 230, green: 223, blue: 209, alpha: 0.28)
                square.layer.borderColor=UIColor.white.cgColor
                square.tag = i*10 + j
                //square.text="\(i*10+j)"
                square.layer.borderWidth=1
                square.layer.masksToBounds=true
                square.layer.cornerRadius=4
                self.view.addSubview(square)
                squares.append(square)
                squareStatus.append(0)
            }
        }
    }

    //上一次的类型,防止和临近的相同
    var tmpNumber:Int = 0
    
    //MARK: 随机产生 1-6 中的数字
    func randomNumber() -> Int {

        var type = Int(arc4random()%6)+1
        
        if type == tmpNumber {//如果和上一次相同重新产生随机数
            type = randomNumber()
        }else{
            if type == 6 {
                return 9
            }
            
            //这一次的类型赋给tmpType
            tmpNumber = type
        }
        return type
    }
    
    
    
    //MARK: 格子动画
    func squareAnimation() {
        for i in 0..<10 {
            for j in 0..<10 {
                let square = squares[i*10+j] as UIView
                //放大缩小
                UIView.animate(withDuration: 0.1, delay: 0.008*Double(i*j), usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveLinear, animations: {
                    square.transform = CGAffineTransform.init(scaleX: 1.2, y: 1.2)
                }) { (finished) in
                    UIView.animate(withDuration: 0.1, animations: {
                        square.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
                    }) { (finished) in
                        if (i*j == 81) {
                            //随机产生三个不同类型的方块
                            self.produceDiamonds()
                        }
                    }
                }
                
                //颜色变深
                UIView.animate(withDuration: 0.1, animations: {
                    square.backgroundColor = customColor(red: 230, green: 223, blue: 209, alpha: 0.5)
                }) { (finished) in
                    UIView.animate(withDuration: 0.1, animations: {
                        square.backgroundColor = customColor(red: 230, green: 223, blue: 209, alpha: 0.28)
                    }) { (finished) in
                        
                    }
                }
                
                //边框消失
                UIView.animate(withDuration: 0.1, delay: 0.008*Double(i*j), options: .curveLinear, animations: {
                    square.layer.borderWidth=0
                    }, completion:{ (finished) -> Void in
                        //边框出现
                        UIView.animate(withDuration: 0.1, delay: 0.008*Double(i*j), options: .curveLinear, animations: { () -> Void in
                            square.layer.borderWidth=1
                            }, completion: nil)
                        
                })
            }
            
        }
    }
    
    //MARK: 随机产生三个不同类型的方块
    //保证6种方块几率一样
    //方向随机
    // + + + [    ]
    func produceDiamonds() {
        
        let space = CGFloat(50)
        
        let diamondWidth =  (gameView.frame.size.width-30*4) / 3.0
        
        for i in 0...2 {
            
            let number = randomNumber() //产生随机数 1-6
            
            let diamond = Diamond(frame: CGRect(x: 0, y: 0, width: diamondWidth, height: diamondWidth))
            
            diamond.number = DiamondNumber(rawValue: number)! //将随机数 方块个数 赋给 diamond
            
            self.view.addSubview(diamond)
            
            //位置Y
            let centerY = SCREEN_SIZE.height-(SCREEN_SIZE.height - gameView.frame.size.height)/4.0
            //位置X
            var centerX = CGFloat(0)
            
            if i==1 {
                centerX = -SCREEN_SIZE.width/2.0
            }
            if i==2 {
                centerX = -SCREEN_SIZE.width/2.0 - diamondWidth - space
            }
            if i==0 {
                centerX = -SCREEN_SIZE.width/2.0 + diamondWidth + space
            }
            
            diamond.center = CGPoint(x: centerX, y: centerY)
            
            //动画
            UIView.animate(withDuration: 0.46, delay: 0.15*Double(i), usingSpringWithDamping: 0.96, initialSpringVelocity: 0.89, options: .curveLinear, animations: {
                diamond.center.x += SCREEN_SIZE.width
                }, completion: { (finished) -> Void in
                    diamond.setCenter()
            })
            
            diamond.tag = DIAMOND_TAG + i
            
            //MARK: 如果diamonds为空 重新创建
            diamond.emptyCallBack(callBack: {
               self.produceDiamonds()
            })
            
            //MARK: gameOver 时
            diamond.gameOverCallBack(callBack: {
                self.gameOver()
            })
            
            diamond.reloadScoreCallBack(callBack: {
                self.statusBar.reloadScore()
            })
            
            diamonds.append(diamond)
        }
    }
    
    var menu : MenuView!
    
    func gameOver() {
        
       
        LYSoundManager.manager.stopMusic()
        
        if menu != nil {
            if menu.isShow == true {
                return
            }
        }
        
        menu = MenuView(frame: UIScreen.main.bounds)
        
        menu.showEndMenu()
        
        //计分板
        menu.scoreCallBack(callBack: {
            LYProgressHUD.showMessage(message: "暂无排名!")
        })
        
        //Home
        menu.settingCallBack(callBack: {
            self.dismiss(animated: false, completion: nil)
            self.setUpData()
            self.menu.dismiss()
        })
        
        //重新开始
        menu.startCallBack(callBack: {
            self.statusBar.reloadBestScore()
            self.setUpData()
            self.squareAnimation()
            self.menu.dismiss()
            LYSoundManager.manager.playDefaultBGM()
        })
        
        //分享
        menu.shareCallBack(callBack: {
            var shareView:LYShareView!
            shareView = LYShareView(frame: CGRect.zero)
            shareView.shareActionCallBack(btnCallBack: { (index) -> () in
                let share = Share()
                var type:String!
                switch index {
                case 0: type = nil
                case 1: type = SLServiceTypeSinaWeibo
                case 2: type = SLServiceTypeTencentWeibo
                default :break
                }
                share.shareTo(type: type, image: UIImage(named: "Icon"), text: "这个游戏好好玩啊!", vc: self)
            })
            self.view.window!.addSubview(shareView)
            
        })
        
        self.view.window!.addSubview(menu)
     
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        selfView.backgroundColor = LYColor.BackColor()
        squareAnimation()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        LYSoundManager.manager.stopMusic()
    }
    
    //初始化数据
    func setUpData() {
        
        for sq in newSquares {
            sq.removeFromSuperview()
        }
        
        for i in 0...99 {
            squareStatus[i]=0
        }
        
        for diamond in diamonds {
            diamond.removeFromSuperview()
        }
        
        DataCenter.setNowScore(score: 0)
        
        statusBar.reloadScore()
        
        newSquares.removeAll(keepingCapacity: false)
        
        diamonds.removeAll(keepingCapacity: false)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
